package eo.builder.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * 
 * 
 * @author takeshi
 * 
 */
public final class XMLReaderHelper {

    private DocumentBuilderFactory builderFactory;

    {
        // always use default xml parser
        builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
    }

    public XMLReaderHelper() {
    }

    public Document buildDom(final InputStream input)
            throws ParserConfigurationException, SAXException, IOException {
        if (input == null) {
            return null;
        }
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        return builder.parse(input);
    }

    public Document buildDomForResource(final String resource,
            final ClassLoader classLoader) throws ParserConfigurationException,
            SAXException, IOException {
        return this.buildDom(this.findSourceForString(resource, classLoader));
    }

    private InputStream findSourceForString(final String url,
            ClassLoader classLoader) {
        InputStream source = classLoader.getResourceAsStream(url);
        if (source != null) {
            return source;
        }
        // might be a file...
        File file = new File(url);
        if (file.exists()) {
            try {
                return new FileInputStream(file);
            } catch (FileNotFoundException e) {
                return null;
                // ignore exception
            }
        }
        return null;
    }

}
